import javax.xml.parsers.DocumentBuilder;

import massim.agent.AbstractAgent;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class Architecture extends AbstractAgent {

	public BeliefBase beliefs;
	private EnvState envState;
	
	public Architecture() {
		super();
		start();
	}
	
	@Override
	public void processLogIn() {
		super.processLogIn();
	}
	
	@Override
	public void processSimulationStart(Element perception, long currenttime) {
		super.processSimulationStart(perception, currenttime);
	}
	
	@Override
	public void processRequestAction(Element perception, Element target,
			long currenttime, long deadline) {
		EnvState envState = new EnvState();
		
		NodeList xmlCells = perception.getChildNodes();
		for (int i = 0; i < xmlCells.getLength(); i++) {
			Node xmlCell = xmlCells.item(i);
			NamedNodeMap attributes = xmlCell.getAttributes();
			NodeList childNodes = xmlCell.getChildNodes();
			
			Cell cell = new Cell();
			cell.x = Integer.parseInt(attributes.getNamedItem("x").toString());
			cell.y = Integer.parseInt(attributes.getNamedItem("y").toString());
			cell.state = childNodes.item(0).toString();
			
			getEnvState().cells.add(cell);
		}
		
		responseId = perception.getAttribute("id");
		
		setEnvState(envState);
	}

	private String responseId;
	
	public void sendAction(Action a) {
		// converter action para xml (doc).
		try {
			DocumentBuilder documentBuilder = documentbuilderfactory.newDocumentBuilder();
			// transformer = TransformerFactory.newInstance().newTransformer();
			
			Document doc = documentBuilder.newDocument();
			Element el_response = doc.createElement("message");

			el_response.setAttribute("type", "action");
			doc.appendChild(el_response);

			Element el_action = doc.createElement("action");
			if (a != null) {
				el_action.setAttribute("type", a.actionText);
			}
			el_action.setAttribute("id", responseId);
			el_response.appendChild(el_action);
			
			sendDocument(doc);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void processSimulationEnd(Element perception, long currenttime) {
		super.processSimulationEnd(perception, currenttime);
	}

	public synchronized EnvState getEnvState() {
//		if (envState == null)
//			wait();
		
//		try {
			return envState;
//		} finally {
//			envState = null;
//		}		 
	}

	public synchronized void setEnvState(EnvState envState) {
//		if (envState != null)
//			wait();
		
		this.envState = envState;
	}
}